package com.mc.moring.main;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.axsy.ddoo.func.record.adapter.TradeHistoryAdapter;
import com.google.gson.Gson;
import com.mc.moring.R;
import com.mc.moring.app.LogUtils;
import com.mc.moring.base.BaseActivity;
import com.mc.moring.base.HttpCallback;
import com.mc.moring.bean.MyTradeListBean;
import com.mc.moring.main.modle.PermisosModle;
import com.mc.moring.util.DateFormatUtils;
import com.mc.moring.util.PointMgr;
import com.mc.moring.util.TimeUtils;
import com.mc.moring.util.ToastUtils;
import com.mc.moring.view.CustomDatePicker;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;


import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MyTradeActivity extends BaseActivity {
    SmartRefreshLayout refresh;
    LinearLayout ll_nodata;
    RecyclerView mRecyclerView;
    private TradeHistoryAdapter followAdapter;
    private int pageIndex = 1;
    private ImageButton abBackIBtn;
    private TextView abTitleTV, tv_start, tv_end;
    private CustomDatePicker mDatePicker;
    private Set<String> loadedDataIds = new HashSet<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.logE("my trade page");
        setContentView(R.layout.activity_my_loan);//activity_msg
        PointMgr.INSTANCE.sendEvent("cl_person_infoof-9_open");
        Log.e("PointMgr.INSTANCE.sendEvent","cl_person_infoof-9_open");
        PointMgr.INSTANCE.sendEvent("cl_person_infoof-8_open");
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-8_open");
        refresh = findViewById(R.id.swipeLayout);
        mRecyclerView = findViewById(R.id.recycler_view);
        abBackIBtn = findViewById(R.id.abBackIBtn);
        abTitleTV = findViewById(R.id.abTitleTV);
        ll_nodata = findViewById(R.id.ll_nodata);
        tv_start = findViewById(R.id.tv_start);
        tv_end = findViewById(R.id.tv_end);
        abTitleTV.setText("Registro de la transacción");
        long currentTimeMillis = System.currentTimeMillis();
        Date currentDate = new Date(currentTimeMillis);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.MONTH, -2);
        String defaultStartDate = DateFormatUtils.formatTradeDate(calendar.getTime());
        tv_start.setText(defaultStartDate);
        tv_end.setText(TimeUtils.timeStamp2Date(String.valueOf(Integer.parseInt(TimeUtils.timeStamp())+"000"), "dd-MM-yyyy"));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(MyTradeActivity.this));
        followAdapter = new TradeHistoryAdapter();
        mRecyclerView.setAdapter(followAdapter);
        pageIndex = 1;
        loadData(pageIndex);
        abBackIBtn.setOnClickListener(v -> finish());
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh.finishRefresh();
                pageIndex = 1;
                loadData(pageIndex);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh.finishLoadMore();
                pageIndex++;
                loadData(pageIndex);
            }
        });
        tv_start.setOnClickListener(v -> {
            initDatePicker(1);
            mDatePicker.show(System.currentTimeMillis());
        });
        tv_end.setOnClickListener(v -> {
            initDatePicker(2);
            mDatePicker.show(System.currentTimeMillis());
        });
    }

    private boolean isDateCorrect(String dateStarStr, String dateEndStr) {
        try {
            Date dateStart = DateFormatUtils.convertStringToDate(dateStarStr);
            Date dateEnd = DateFormatUtils.convertStringToDate(dateEndStr);
            if (dateStart != null && dateEnd != null) {
                if (dateEnd.after(dateStart)) {
                    return true;
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    private void initDatePicker(int index) {
        long beginTimestamp = DateFormatUtils.str2Long("2000-1-1", false);
        long endTimestamp = DateFormatUtils.str2Long("2100-12-30", false);
        mDatePicker = new CustomDatePicker(MyTradeActivity.this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                if (index == 1) {
                    if (!TextUtils.isEmpty(tv_end.getText())) {
                        if (!isDateCorrect(DateFormatUtils.convertTimestampToString(timestamp), tv_end.getText().toString())) {
                            ToastUtils.showShort(MyTradeActivity.this, "Por favor seleccione la fecha correcta");
                            return;
                        }
                        tv_start.setText(DateFormatUtils.convertTimestampToString(timestamp));
                    }
                } else {
                    if (!TextUtils.isEmpty(tv_start.getText())) {
                        if (!isDateCorrect(tv_start.getText().toString(), DateFormatUtils.convertTimestampToString(timestamp))) {
                            ToastUtils.showShort(MyTradeActivity.this, "Por favor seleccione la fecha correcta");
                            return;
                        }
                    }
                    tv_end.setText(DateFormatUtils.convertTimestampToString(timestamp));
                }
                pageIndex = 1;
                loadData(pageIndex);
            }

            @Override
            public void onTimeListened(long timestamp) {

            }
        }, beginTimestamp, endTimestamp);
        mDatePicker.setCancelable(true);
        mDatePicker.setCanShowPreciseTime(false);
        mDatePicker.setScrollLoop(false);
        mDatePicker.setCanShowAnim(false);
    }

    private Calendar getStartCalendar() {
        long currentTimeMillis = System.currentTimeMillis();
        Date currentDate = new Date(currentTimeMillis);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.MONTH, -2);
        return calendar;
    }

    private Calendar getEndCalendar() {
        long currentTimeMillis = System.currentTimeMillis();
        Date currentDate = new Date(currentTimeMillis);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        return calendar;
    }

    @Override
    public Activity getActivity() {
        return null;
    }

    @Override
    public void initView() {

    }

    private void loadData(int mPageIndex) {
        if (TextUtils.isEmpty(tv_start.getText())) {
            String defaultStartDate = DateFormatUtils.formatTradeDate(getStartCalendar().getTime());
            tv_start.setText(defaultStartDate);
        }
        if (TextUtils.isEmpty(tv_end.getText())) {
            String defaultEndDate = DateFormatUtils.formatTradeDate(getEndCalendar().getTime());
            tv_end.setText(defaultEndDate);
        }

        Map<String, String> map = new HashMap<>();
        map.put("startDate",TimeUtils.date2LoanHistoryFormatDate(tv_start.getText().toString()));
        map.put("endDate",TimeUtils.date2LoanHistoryFormatDate(tv_end.getText().toString()));
        map.put("pageIndex", mPageIndex + "");
        map.put("pageSize", 20 + "");
        showLoading();
        PermisosModle.Companion.getInstant().getCashFlow(map, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                LogUtils.logE("----user trade list>" + data);
                LogUtils.logE("----user trade list >pageIndex:" + mPageIndex);
                MyTradeListBean bean = new Gson().fromJson(data, MyTradeListBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (bean.getCode().equals("0000")) {
                            if (mPageIndex == 1 && bean.getData().size() == 0) {
                                ll_nodata.setVisibility(View.VISIBLE);
                                refresh.setVisibility(View.GONE);
                                return;
                            }
                            ll_nodata.setVisibility(View.GONE);
                            refresh.setVisibility(View.VISIBLE);
                            followAdapter.submitList(bean.getData());
                            Log.e("----mPageIndex", String.valueOf(mPageIndex));
                            Log.e("----beanData.size", String.valueOf(bean.getData().size()));
                            Log.e("----beanData",bean.getData().toString());
                        } else {
                            ToastUtils.showShort(MyTradeActivity.this, bean.getMsg());
                        }
                    }
                });
                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                LogUtils.logE("user trade request fail>" + e);
                hideLoading();
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void onStop(){
        super.onStop();
        hideLoading();
    }
}
